<?php

namespace app\admin\service;

use app\admin\model\Admin;
use app\lib\exception\Admin as AdminException;
use app\admin\model\Admin as AdminModel;

class Auth
{
    /**
     * 字符串去重
     * @param $str
     * @return string
     */
    static function unique($str): string
    {
        $arr = explode(',', $str);
        $arr = array_unique($arr);
        $data = implode(',', $arr);
        return trim($data);
    }

    /**
     * 登录实现
     * @param $username
     * @param $password
     * @return array|false
     * @throws AdminException
     */
    static function login($username, $password)
    {
        if (empty($username)) return false;

        // 检测用户名或邮箱、手机号是否存在
        $admin = AdminModel::getByUsername($username);
        if (!$admin) {
            throw new AdminException(['msg' => '账户不正确']);
        }

        if ($admin['status'] != 1) {
            throw new AdminException(['msg' => '账户已经被锁定']);
        }

        if ($admin->password != self::getEncryptPassword($password, $admin->salt)) {
            throw new AdminException(['msg' => '密码不正确']);
        }

        $save_data = [
            'login_ip' => get_client_ip(),
            'login_time' => date('Y-m-d H:i:s')
        ];
        $res = (new Admin)->where('id=' . $admin->id)->update($save_data);
        if ($res !== false) {
            $admin = $admin->visible(['id'])->toArray();
            return $admin;
        } else {
            throw new AdminException(['msg' => '账户或密码不正确']);
        }
    }


    /**
     * 密码加密
     * @param $password
     * @param string $salt
     * @return string
     */
    static function getEncryptPassword($password, string $salt = ''): string
    {
        return md5(md5($password) . $salt);
    }

    /**
     * 获取用户信息
     * @param $id
     * @return array
     * @throws AdminException
     */
    static function getInfo($id): array
    {
        $find = (new AdminModel)->where('id', $id)->findOrEmpty();
        if ($find->isEmpty()) throw new AdminException(['msg' => '账户不正确']);
        if ($find->status != 1) throw new AdminException(['msg' => '账户状态失效']);
        $find = $find->visible(['id', 'username', 'nickname', 'phone','role_ids','status'])->toArray();
        return $find;
    }

}